<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="1、KafkaProducer 概述根据 KafkaProducer 类上的注释上来看 KafkaProducer 具有如下特征：  KafkaProducer 是线程安全的，可以被多个线程交叉使用。 KafkaProducer 内部包含一个缓存池，存放待发送消息，即 ProducerRecord 队列，与此同时会开启一个IO线程将 ProducerRecord 对象发送到 Kafka 集群。 K">
<meta property="og:type" content="article">
<meta property="og:title" content="初识 Kafka Producer 生产者">
<meta property="og:url" content="https://www.codingw.net/posts/b579d244.html">
<meta property="og:site_name" content="中间件兴趣圈">
<meta property="og:description" content="1、KafkaProducer 概述根据 KafkaProducer 类上的注释上来看 KafkaProducer 具有如下特征：  KafkaProducer 是线程安全的，可以被多个线程交叉使用。 KafkaProducer 内部包含一个缓存池，存放待发送消息，即 ProducerRecord 队列，与此同时会开启一个IO线程将 ProducerRecord 对象发送到 Kafka 集群。 K">
<meta property="og:locale">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20191103130908591.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70">
<meta property="article:published_time" content="2020-10-24T14:56:01.000Z">
<meta property="article:modified_time" content="2021-04-26T10:00:05.236Z">
<meta property="article:author" content="中间件兴趣圈">
<meta property="article:tag" content="中间件">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img-blog.csdnimg.cn/20191103130908591.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://www.codingw.net/posts/b579d244.html"/>





  <title>初识 Kafka Producer 生产者 | 中间件兴趣圈</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">中间件兴趣圈</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">微信搜『中间件兴趣圈』，回复『Java』获取200本优质电子书</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://www.codingw.net/posts/b579d244.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="中间件兴趣圈">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">初识 Kafka Producer 生产者</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-10-24T22:56:01+08:00">
                2020-10-24
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/kafka/" itemprop="url" rel="index">
                    <span itemprop="name">kafka</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/posts/b579d244.html" class="leancloud_visitors" data-flag-title="初识 Kafka Producer 生产者">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <div id="vip-container"><h2 id="1、KafkaProducer-概述"><a href="#1、KafkaProducer-概述" class="headerlink" title="1、KafkaProducer 概述"></a>1、KafkaProducer 概述</h2><p>根据 KafkaProducer 类上的注释上来看 KafkaProducer 具有如下特征：</p>
<ul>
<li>KafkaProducer 是线程安全的，可以被多个线程交叉使用。</li>
<li>KafkaProducer 内部包含一个缓存池，存放待发送消息，即 ProducerRecord 队列，与此同时会开启一个IO线程将 ProducerRecord 对象发送到 Kafka 集群。</li>
<li>KafkaProducer 的消息发送 API send 方法是异步，只负责将待发送消息 ProducerRecord 发送到缓存区中，立即返回，并返回一个结果凭证 Future。</li>
<li>acks<br>KafkaProducer 提供了一个核心参数 acks 用来定义消息“已提交”的条件(标准)，就是 Broker 端向客户端承偌已提交的条件，可选值如下：<ul>
<li>0<br>表示生产者不关系该条消息在 broker 端的处理结果，只要调用 KafkaProducer 的 send 方法返回后即认为成功，显然这种方式是最不安全的，因为 Broker 端可能压根都没有收到该条消息或存储失败。</li>
<li>all 或 -1<br>表示消息不仅需要 Leader 节点已存储该消息，并且要求其副本（准确的来说是 ISR 中的节点）全部存储才认为已提交，才向客户端返回提交成功。这是最严格的持久化保障，当然性能也最低。</li>
<li>1<br>表示消息只需要写入 Leader 节点后就可以向客户端返回提交成功。</li>
</ul>
</li>
</ul>
<span id="more"></span>

<ul>
<li>retries<br>kafka 在生产端提供的另外一个核心属性，用来控制消息在发送失败后的重试次数，设置为 0 表示不重试，重试就有可能造成消息在发送端的重复。</li>
<li>batch.size<br>  kafka 消息发送者为每一个分区维护一个未发送消息积压缓存区，其内存大小由batch.size指定，默认为 16K。<br>  但如果缓存区中不足100条，但发送线程此时空闲，是需要等到缓存区中积满100条才能发送还是可以立即发送呢？默认是立即发送，即 batch.size 的作用其实是客户端一次发送到broker的最大消息数量。</li>
<li>linger.ms<br>  ​    为了提高 kafka 消息发送的高吞吐量，即控制在缓存区中未积满 batch.size  时来控制 消息发送线程的行为，是立即发送还是等待一定时间，如果linger.ms 设置为 0表示立即发送，如果设置为大于0，则消息发送线程会等待这个值后才会向broker发送。该参数者会增加响应时间，但有利于增加吞吐量。有点类似于 TCP 领域的 Nagle 算法。</li>
<li>buffer.memory<br>用于控制消息发送者缓存的总内存大小，如果超过该值，往缓存区中添加消息会被阻塞，具体会在下文的消息发送流程中详细介绍，阻塞的最大时间可通过参数 max.block.ms 设置，阻塞超过该值会抛出超时异常。</li>
<li>key.serializer<br>指定 key 的序列化处理器。</li>
<li>value.serializer<br>指定 消息体的序列化处理器。</li>
<li>enable.idempotence<br>从 kafka0.11版本开始，支持消息传递幂等，可以做到消息只会被传递一次，通过 enable.idempotence 为 true 来开启。如果该值设置为 true，其 retries 将设置为 Integer.MAX_VALUE，acks 将被设置为 all。为了确保消息发送幂等性，必须避免应用程序端的任何重试，并且如果消息发送API如果返回错误，应用端应该记录最后成功发送的消息，避免消息的重复发送。</li>
</ul>
<p>从Kafka 0.11开始，kafka 也支持事务消息。</p>
<h2 id="2、KafkaProducer-类图"><a href="#2、KafkaProducer-类图" class="headerlink" title="2、KafkaProducer 类图"></a>2、KafkaProducer 类图</h2><p><img src="https://img-blog.csdnimg.cn/20191103130908591.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"><br>在 Kafka  中，生产者通过接口 Producer 定义，通过该接口的方法，我们基本可以得知 KafkaProducer 将具备如下基本能力：</p>
<ul>
<li>void initTransactions()<br>初始化事务，如果需要使用事务方法，该方法必须首先被调用。</li>
<li>void beginTransaction()<br>开启事务。</li>
<li>void sendOffsetsToTransaction(Map&lt; TopicPartition, OffsetAndMetadata&gt; offsets,String consumerGroupId)<br>向消费组提交当前事务中的消息偏移量，将在介绍 Kafka 事务相关文章中详细介绍。</li>
<li>void commitTransaction()<br>提交事务。</li>
<li>void abortTransaction()<br>回滚事务。</li>
<li>Future&lt; RecordMetadata&gt; send(ProducerRecord&lt;K, V&gt; record)<br>消息发送，该方法默认为异步发送，如果要实现同步发送的效果，对返回结果调用  get 方法即可，该方法将在下篇文章中详细介绍。</li>
<li>Future&lt; RecordMetadata&gt; send(ProducerRecord&lt;K, V&gt; record, Callback callback)<br> ​    消息发送，支持回调。</li>
<li>void flush()<br>忽略 linger.ms 的值，直接唤醒发送线程，将缓冲区中的消息全部发送到 broker。</li>
<li>List&lt; PartitionInfo&gt; partitionsFor(String topic)<br>获取 topic 的路由信息（分区信息）。</li>
<li>Map&lt; MetricName, ? extends Metric&gt; metrics()<br>获取由生产者收集的统计信息。</li>
<li>void close()<br>关闭发送者。</li>
<li>void close(Duration timeout)<br>定时关闭消息发送者。</li>
</ul>
<p>上面的方法我们会根据需要在后续文章中进行详细的介绍。接下来我们看一下 KafkaProducer 的核心属性的含义。</p>
<ul>
<li>String clientId<br>客户端ID。在创建 KafkaProducer 时可通过 client.id 定义 clientId，如果未指定，则默认 producer- seq，seq 在进程内递增，强烈建议客户端显示指定 clientId。</li>
<li>Metrics metrics<br>度量的相关存储容器，例如消息体大小、发送耗时等与监控相关的指标。</li>
<li>Partitioner partitioner<br>分区负载均衡算法，通过参数 partitioner.class 指定。</li>
<li>int maxRequestSize<br>调用 send 方法发送的最大请求大小，包括 key、消息体序列化后的消息总大小不能超过该值。通过参数 max.request.size 来设置。</li>
<li>long totalMemorySize<br>生产者缓存所占内存的总大小，通过参数 buffer.memory 设置。</li>
<li>Metadata metadata<br>元数据信息，例如 topic 的路由信息，由 KafkaProducer 自动更新。</li>
<li>RecordAccumulator accumulator<br>消息记录累积器，将在消息发送部分详细介绍。</li>
<li>Sender sender<br>用于封装消息发送的逻辑，即向 broker 发送消息的处理逻辑。</li>
<li>Thread ioThread<br>用于消息发送的后台线程，一个独立的线程，内部使用 Sender 来向 broker 发送消息。</li>
<li>CompressionType compressionType<br>压缩类型，默认不启用压缩，可通过参数 compression.type 配置。可选值：none、gzip、snappy、lz4、zstd。</li>
<li>Sensor errors<br>错误信息收集器，当成一个 metrics，用来做监控的。</li>
<li>Time time<br>用于获取系统时间或线程睡眠等。</li>
<li>Serializer&lt; K&gt; keySerializer<br>用于对消息的 key 进行序列化。</li>
<li>Serializer&lt; V&gt; valueSerializer<br>对消息体进行序列化。</li>
<li>ProducerConfig producerConfig<br>生产者的配置信息。</li>
<li>long maxBlockTimeMs<br>最大阻塞时间，当生产者使用的缓存已经达到规定值后，此时消息发送会阻塞，通过参数 max.block.ms 来设置最多等待多久。</li>
<li>ProducerInterceptors&lt;K, V&gt; interceptors<br>生产者端的拦截器，在消息发送之前进行一些定制化处理。</li>
<li>ApiVersions apiVersions<br>维护 api 版本的相关元信息，该类只能在 kafka 内部使用。</li>
<li>TransactionManager transactionManager<br>kafka 消息事务管理器。</li>
<li>TransactionalRequestResult initTransactionsResult<br>kafka 生产者事务上下文环境初始结果。</li>
</ul>
<p>经过上面的梳理，详细读者朋友对 KafkaProducer 消息生产者有了一个大概的认识，下一篇会重点介绍消息发送流程。接下来我们以一个简单的示例结束本文的学习。</p>
<h2 id="3、KafkaProducer-简单示例"><a href="#3、KafkaProducer-简单示例" class="headerlink" title="3、KafkaProducer 简单示例"></a>3、KafkaProducer 简单示例</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> persistent.prestige.demo.kafka;</span><br><span class="line"><span class="keyword">import</span> org.apache.kafka.clients.producer.KafkaProducer;</span><br><span class="line"><span class="keyword">import</span> org.apache.kafka.clients.producer.Producer;</span><br><span class="line"><span class="keyword">import</span> org.apache.kafka.clients.producer.ProducerRecord;</span><br><span class="line"><span class="keyword">import</span> org.apache.kafka.clients.producer.RecordMetadata;</span><br><span class="line"><span class="keyword">import</span> java.util.Properties;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.Future;</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">KafkaProducerTest</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span></span>&#123;</span><br><span class="line">        Properties props = <span class="keyword">new</span> Properties();</span><br><span class="line">        props.put(<span class="string">&quot;bootstrap.servers&quot;</span>, <span class="string">&quot;localhost:9092,localhost:9082,localhost:9072,&quot;</span>);</span><br><span class="line">        props.put(<span class="string">&quot;acks&quot;</span>, <span class="string">&quot;all&quot;</span>);</span><br><span class="line">        props.put(<span class="string">&quot;key.serializer&quot;</span>, <span class="string">&quot;org.apache.kafka.common.serialization.StringSerializer&quot;</span>);</span><br><span class="line">        props.put(<span class="string">&quot;value.serializer&quot;</span>, <span class="string">&quot;org.apache.kafka.common.serialization.StringSerializer&quot;</span>);</span><br><span class="line">        Producer&lt;String, String&gt; producer = <span class="keyword">new</span> KafkaProducer&lt;&gt;(props);</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">100</span>; i++) &#123;</span><br><span class="line">                Future&lt;RecordMetadata&gt;  future = producer.send(<span class="keyword">new</span> ProducerRecord&lt;String, String&gt;(<span class="string">&quot;TOPIC_ORDER&quot;</span>, Integer.toString(i), Integer.toString(i)));</span><br><span class="line">                RecordMetadata recordMetadata = future.get();</span><br><span class="line">                System.out.printf(<span class="string">&quot;offset:&quot;</span> + recordMetadata.offset());</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Throwable e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            producer.close();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>本文就介绍到这里，其主要的目的是了解Kafka 的 Producer，引出后续需要学习的内容，下一篇将重点讲述 Kafka 消息的发送流程，敬请关注。</p>
</div>

			<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
			<script>
			var isMobile = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i);
			if (!isMobile) {
			    var btw = new BTWPlugin();
			    btw.init({
			        "id": "vip-container",
			        "blogId": "18019-1573088808868-542",
			        "name": "中间件兴趣圈",
			        "qrcode": "https://img-blog.csdnimg.cn/20190314214003962.jpg",
			        "keyword": "more"
			    });
			}
			</script>
		
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/posts/d9d4c345.html" rel="next" title="初始 Kafka Consumer 消费者">
                <i class="fa fa-chevron-left"></i> 初始 Kafka Consumer 消费者
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/posts/eab70bff.html" rel="prev" title="Netty4 ChannelHandler 概述">
                Netty4 ChannelHandler 概述 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">139</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1%E3%80%81KafkaProducer-%E6%A6%82%E8%BF%B0"><span class="nav-number">1.</span> <span class="nav-text">1、KafkaProducer 概述</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2%E3%80%81KafkaProducer-%E7%B1%BB%E5%9B%BE"><span class="nav-number">2.</span> <span class="nav-text">2、KafkaProducer 类图</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3%E3%80%81KafkaProducer-%E7%AE%80%E5%8D%95%E7%A4%BA%E4%BE%8B"><span class="nav-number">3.</span> <span class="nav-text">3、KafkaProducer 简单示例</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">中间件兴趣圈</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("NNEhOL0iOcflg8f1U3HUqiCq-gzGzoHsz", "7kSmkbbb3DktmHALlShDsBUF");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
